package com.example.task.service.impl;


import com.example.task.dao.OrderDao;
import com.example.task.dao.TurnoverDao;
import com.example.task.entity.Order;
import com.example.task.service.MessgeService;
import com.example.task.service.OrderService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sunny
 * @desc 任务类 实现类
 */
@Service("OrderService")
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderDao orderMapper;

    @Resource
    private TurnoverDao turnoverMapper;


    @Resource
    private MessgeService messgeService;

    /**
     * 3. 定时每日0点开始扫描订单表，对于前一天已完成的订单，将订单金额统计到上一天的营业额。
     *
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void findPayOrderByTime() {
        // step1 获取完成订单
        List<Order> payOrders = orderMapper.findPayOrderByTime();
        // step2 遍历完成订单 计算成交金额
        int totalMount = payOrders.stream()
                .mapToInt(Order::getPayAmount)
                .sum(); // 计算总和

        // step3 查前一天营业额
        int prevMount = turnoverMapper.findPrevMount();
        // step4 营业额累加 更新
        turnoverMapper.updateNewMount(prevMount+totalMount);

    }

    /**
     * 4. 对于超过24小时未支付的订单，做自动取消并通知给用户的功能。（通知功能可以使用伪代码）
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void findUnpayOrderByTime() {
        // step1 获取24小时未支付订单
        List<Order> unPayOrders = orderMapper.findUnpayOrderByTime();

        // step2 批量取消订单
        List<String> ids = unPayOrders.stream().map(Order::getId).collect(Collectors.toList());
        assert !CollectionUtils.isEmpty(ids);
        orderMapper.batchUpdateState(ids);

        // step3 通知客户
        List<String> userIds = unPayOrders.stream().map(Order::getUserId).collect(Collectors.toList());
        // 批量发消息
        messgeService.sent(userIds,"超时取消订单");

    }

    @Override
    public Order findOrderById(String id) {
        Order order = orderMapper.selectById(id);
        if(null == order){
            order = new Order();
            order.setMessage("订单不存在");
        }
        return order;
    }
}
